package alogrithm;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @author lbw
 * @version 1.0
 * @date 2021/10/18 19:24
 */
public class PermuteUnique {
    public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        if (num == null || num.length < 1) {
            return res;
        }
        Arrays.sort(num);
        dfs(res, num, 0);
        return res;

    }

    private void dfs(ArrayList<ArrayList<Integer>> res, int[] num, int i) {
        if (i == num.length) {
            ArrayList<Integer> list = new ArrayList<>();
            for (int n : num) {
                list.add(n);
            }
            res.add(list);
        }
        Set<Integer> set = new HashSet<>();
        for (int j = i; j < num.length; ++j) {
            if (!set.contains(num[j])) {
                set.add(num[j]);
                swap(num, i, j);
                dfs(res, num, i + 1);
                swap(num, i, j);
            }
        }
    }

    private void swap(int[] num, int i, int j) {
        int temp = num[i];
        num[i] = num[j];
        num[j] = temp;
    }
}
